{% extends 'base.html' %}
{% block title %}
    <title>目录管理</title>
{% endblock title %}
{% block customcss %}
    <link rel="stylesheet" href="../../static/ztree/css/bootstrapStyle/bootstrapStyle.css" type="text/css">
    <style>
        .layui-col-md7 {
            border-left:1px solid green;
            height: 450px;
            padding-top: 10%;
            padding-left: 5%;
        }
        #div01 {
            background-color: #ffffff;
            border: 1px solid green;
        }
    </style>
{% endblock customcss %}
{% block content %}
    <div>
        <h1>新增目录结构</h1>
        <hr>
        <div id="div01" class="layui-row layui-col">

             <div class="layui-col-md5" style="border-right:1px solid green;height: 450px;overflow:auto; ">
                <ul id="treeDemo" class="ztree"></ul>
             </div>
            {% if user.level_id == 0 %}
                <div class="layui-col-md7" >
                    <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;添加根目录</h3>
                    <br>
                    <button class="layui-btn" id="btn">
                        <i class="layui-icon">&#xe608;</i> 添加根目录
                    </button>
{#                    <button class="layui-btn" id="btn1">#}
{#                        <i class="layui-icon">&#xe640;</i> 删除根目录#}
{#                    </button>#}
                    <br>
                    <br>
                    <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;操作说明：</h3>
                    <br>
                    <p>1.滑动鼠标至节点位置，弹出操作按钮。</p>
                    <p>2.点击操作按钮，对应增加、修改、删除操作。</p>
                    <p>3.根目录节点不能删除，由超级管理员创建/删除操作。</p>
                    <p>4.目录节点最多三级，如需求多级，请联系超级管理员！</p>
                </div>
            {% else %}
                <div class="layui-col-md7" >
                    <h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;操作说明：</h3>
                    <br>
                    <p>1.滑动鼠标至节点位置，弹出操作按钮。</p>
                    <p>2.点击操作按钮，对应增加、修改、删除操作。</p>
                    <p>3.根目录节点不能删除，由超级管理员创建/删除操作。</p>
                    <p>4.目录节点最多三级，如需求多级，请联系超级管理员！</p>
                </div>
            {% endif %}
        </div>
    </div>
{#    添加根目录form表单#}
    <div class="layui-row" id="add_rootdir_form" style="display: none;margin: 50px auto">
        <div class="layui-col-md10">
            <form class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <input type="text" name="name" lay-verify="username" placeholder="请输入根目录名"
                               autocomplete="off"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="add_rootdir_submit">保存</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

{% endblock content %}
{% block customjs %}
    {#    <script type="text/javascript" src="../../static/ztree/js/jquery.min.js"></script>#}
    <script type="text/javascript" src="../../static/ztree/js/jquery.ztree.core.js"></script>
    <script type="text/javascript" src="../../static/ztree/js/jquery.ztree.excheck.js"></script>
    <script type="text/javascript" src="../../static/ztree/js/jquery.ztree.exedit.js"></script>
    <SCRIPT type="text/javascript">

        //获取cookie中的token
        //csrftoken=aHcZ3FLEGVgRTOBWVsjpcLmh5LZ1vyRnvuuWxd2GxydNOUUkDKhOegK21Fd45Tcc
{#        function getCookie(name) {#}
{#            var r = document.cookie.split("=");#}
{#            return r ? r[1] : undefined;#}
{#        }#}
        // 获取cookie中的token
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        // 给ajax请求设置请求头x-csrftoken
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        layui.use(['form', 'layedit', 'laydate','element','jquery'], function() {
            var form = layui.form,
                layer = layui.layer,
                element = layui.element,
                $ = layui.jquery;
            $(document).on('click', '#btn', function () {
                layer.open({
                    type: 1,
                    shade: 0,
                    {#                  skin: 'layui-layer-rim', //加上边框#}
                    skin: 'demo-class', //加上边框
                    title: '创建根目录',
                    area: ['420px', '240px'], //宽高
                    scrollbar: false,
                    content: $("#add_rootdir_form")
                });
                //监听提交
                form.on('submit(add_rootdir_submit)', function (data) {
                    var valu = data.field['name'];
                    if (valu) {
                        $.ajax({
                            type: "post",
                            url: "/mulu/add_rootdir/",
                            data: data.field,
                            dataType: "json",
{#                            headers:{#}
{#                                "X-CSRFTOKEN":getCookie("csrf_token")#}
{#                            },#}
                            success: function (data) {
                                if (data.code === 0) {
                                    layer.alert('新增根目录成功！', {end: function () {
                                        location.reload()
                                    }});
                                } else if(data.code === 2){
                                    layer.alert('新增失败！根目录名重复，请重试')
                                }
                            }
                        });
                        return false
                    }
                    layer.alert('根目录名字不能为空');
                    return false
                });
            });
        });
        //ztree 插件实现目录结构各功能
        var zNodes = [];
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            check: {
                enable: false,//是否启用复选框
                chkStyle: "checkbox",
                chkboxType: {"Y": "", "N": ""}
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            edit: {
                enable: true,
                showRemoveBtn: setRemoveBtn,
                showRenameBtn: true,
                removeTitle: "删除节点",
                renameTitle: "重命名"
            },
            callback: {//回调方法相关
                //onCheck: onCheck,
                beforeRename: zTreeBeforeRename, //重命名前执行的方法
                beforeRemove: zTreeBeforeRemove,
                //onClick: zTreeOnClick         //单击tree时的方法
            }
        };
        //封装获取目录结构函数get_catalog
        (function () {
            var get_catalog = function () {
                var user_id = {{ request.session.user_id }};
                $.ajax({
                    type: "get",
                    url: "/mulu/catalog/?user_id="+user_id,
                    dataType: "json",
                    success: function (data){
                        $.each(data.data, function (i, item) {
                            if (data.code === 0) {
                                zNodes.push({id: item.id, pId: item.parent_id, name: item.name, open: true,isParent:true})
                            }else {
                                layer.msg("数据库异常！请联系管理员。")
                            }
                        });
                        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                    }
                });
                return false;
{#                $.post('/mulu/catalog/',{'user_id':user_id}, function (resp) {#}
{#                    $.each(resp.data, function (i, item) {#}
{#                        if (resp.msg == 'success') {#}
{#                            zNodes.push({id: item.id, pId: item.parent_id, name: item.name, open: true})#}
{#                        }#}
{#                    });#}
{#                    $.fn.zTree.init($("#treeDemo"), setting, zNodes);#}
{#                });#}
            };
            window.get_catalog = get_catalog;
        }());
        //获取数据库目录数据
        get_catalog();

        var newCount = 1;
        var user_id = {{ request.session.user_id }}
        function addHoverDom(treeId, treeNode) {
            //第三级不显示添加按钮
            var level = treeNode.level + 1;
            if (level == 3) {
                return false;
            }

            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='增加子节点' onfocus='this.blur();'></span>";
            sObj.after(addStr);

            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function () {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                var jsondata = {"pid":treeNode.id};
                var name = treeNode.name;
                $.ajax({
                    type: "put",
                    url: "/mulu/catalog/",
                    data:jsondata,
                    dataType: "json",
                    success: function (data){
                        if (data.code === 0){
                            layer.msg('新增ok');
                            zTree.addNodes(treeNode, {id: data.data[0].id, pId: treeNode.id, name: "新增项" + (newCount++),isParent:true})
                        }else if(data.code === 1) {
                            layer.msg('数据异常，请联系管理员！')
                        }else if (data.code === 2){
                            layer.alert('添加失败！有资源的目录，无法新增子目录。请重试或联系管理员！',{end:function () {
                                location.reload()
                            }});
                        }
                    }
                });
                return false;
            });
        };

        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.tId).unbind().remove();
        };

        //根节点不显示删除按钮
        //判断是否为超级管理员level_id=0，是则显示删除。
        var level_id = {{ request.session.level_id }}
        function setRemoveBtn(treeId, treeNode) {
            if (level_id ) {
                if (treeNode.level === 0) {//根节点不能删除
                    return false;
                } else {
                    return true;
                }
            }else {
                return true;
            }
        };

        //修改节点名称
        function zTreeBeforeRename(treeId, treeNode, newName) {
            var name = newName;
            var patt1 = /\./;
            var result = patt1.test(name);
            if (result){ //判断目录名不能输入'.'符号
                layer.alert('修改失败！目录名不能存在‘.’字符，请重试！',{end:function () {
                                    location.reload()
                                }});
            }else {
                    var jsondata = {'id': treeNode.id, 'name': newName, 'level': treeNode.level}
                    $.ajax({
                        type: "patch",
                        url: "/mulu/catalog/",
                        data:jsondata,
                        dataType: "json",
                        success: function (data){
                            if (data.code === 0){
                                layer.msg('修改成功！');
                            }else if (data.code === 1){
                                layer.alert('数据库异常，修改失败！请重试或联系管理员！',{end:function () {
                                    location.reload()
                                }});
                            }else if (data.code === 2){
                                layer.alert('目录名不能为空！',{end:function () {
                                    location.reload()
                                }});
                            }else if (data.code === 3){
                                layer.alert('修改失败！目录名重复，请重试！',{end:function () {
                                    location.reload()
                                }});
                            }
                        }
                    });
            }

            }
        //删除前回掉函数
        function zTreeBeforeRemove(treeId, treeNode) {
            if (confirm("确定删除吗？")) {
                //alert(treeNode.id); 当前目录节点的id
                var jsondata = {'id': treeNode.id, 'level': treeNode.level};
                $.ajax({
                    type: "delete",
                    url: "/mulu/catalog/",
                    data:jsondata,
                    dataType: "json",
                    success: function (data){
                        if (data.code === 0){
{#                            layer.msg('删除成功！');#}
                            layer.alert('删除成功！', {end: function () {
                                location.reload()
                            }});
                        }else if(data.code === 2){
                            layer.alert('有资源的目录无法删除！', {end: function () {
                                location.reload()
                            }})

                        }else if(data.code === 1){
                            layer.alert('数据库异常，删除失败！请重试或联系管理员！',{end:function () {
                                location.reload()
                            }});
                        }
                    }
                });
            } else {
                return false;
            }
        }
{#        复选框选中事件       #}
{#    function onCheck(e,treeId,treeNode) {#}
{#        var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),#}
{#            nodes = treeObj.getCheckedNodes(true);#}
{#        for (var i = 0; i < nodes.length; i++) {#}
{#            layui.use(['form', 'layedit', 'laydate','element','jquery'], function() {#}
{#                var form = layui.form,#}
{#                    layer = layui.layer,#}
{#                    element = layui.element,#}
{#                    $ = layui.jquery;#}
{#                var id = nodes[i].id;#}
{#                $(document).on('click', '#btn1', function () {#}
{#                    $.post("/mulu/remove_catalog/",{'id':id},function (resp) {#}
{#                        if(resp.msg == 'success'){#}
{#                            layer.msg('删除成功');#}
{#                            location.reload()#}
{#                        }else {#}
{#                            layer.msg('删除失败！请重试')#}
{#                        }#}
{#                    })#}
{#                });#}
{#            });#}
{#            alert("节点id:" + nodes[i].id + "节点名称" + nodes[i].name); //获取选中节点的值#}
{#        }#}
{#    }#}

        //-->
    </SCRIPT>
{% endblock %}
